package com.cloudcc.boot.web;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * author : 林贵美 on 2024-04-24
 * 新版单点登陆
 * */
@Configuration
public class OA_LoginService {
	private static Log log = LogFactory.getLog(OA_LoginService.class);
	private static String crmUsername;//用户名
	@Value("${system.userName}")
	public void setUserName(String userName) {
		this.crmUsername = userName;
	}
	private static String crmPass;//crmPass
	@Value("${system.password}")
	public void setPassword(String password) {
		this.crmPass = password;
	}
	private static String safetyMark;//safetyMark
	@Value("${system.safetyMark}")
	public void setSafetyMark(String safetyMark) {
		this.safetyMark = safetyMark;
	}
	private static String clientId;//clientId
	@Value("${system.clientId}")
	public void setClientId(String clientId) {this.clientId = clientId;}
	private static String secretKey;//secretKey
	@Value("${system.secretKey}")
	public void setSecretKey(String secretKey) {
		this.secretKey = secretKey;
	}
	private static String orgId;//orgId
	@Value("${system.orgId}")
	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	public static String url;
	@Value("${system.url}")
	public  void setUrl(String url) {
		this.url = url;
	}

	public OA_LoginService() {
	}

	/**
	 * 单点登录审批
	 * @throws Exception 
	 * 
	 */
	public static JSONObject intocrm(String login_name, String login_pwd) throws Exception {
		JSONObject resultInfo = new JSONObject();
		//判断传入的参数
		if (login_name == null || login_name.equals("") || login_pwd == null || login_pwd.equals("")) {
			resultInfo = new JSONObject();
			resultInfo.put("SuccessFlag", "0");
			resultInfo.put("ErrorMessage", "参数不全");
			resultInfo.put("ReturnData", "");
			log.info(resultInfo);
			return resultInfo;
		}

		//根据审批人域账号查询CRM是否存在对应的用户，存在时获取用户名和密码进行登录
		//获取token
		String adminAccessToken = gettoken(crmUsername);
		//查询CRM是否有数据
		JSONObject jsoncontent = new JSONObject();
		jsoncontent.put("serviceName", "cqlQueryWithLogInfo");
		jsoncontent.put("objectApiName", "ccuser");
		jsoncontent.put("expressions", "select * from ccuser where loginname='" + login_name + "'");

		String resultselectquery = operate(url+"openApi/common", jsoncontent.toString(),adminAccessToken);
		JSONObject select_result = JSONObject.fromObject(resultselectquery);
		String date = select_result.get("data") == null ? "" : select_result.getString("data");
		if (date.length() == 2) {//没有该域账号对应的用户
			resultInfo = new JSONObject();
			resultInfo.put("SuccessFlag", "1");
			resultInfo.put("ErrorMessage", "CRM不存在该账户");
			resultInfo.put("ReturnData", "");
			return resultInfo;
		} else {
			//查询账号密码
			JSONObject jsoncontent1 = new JSONObject();
			jsoncontent1.put("serviceName", "cqlQueryWithLogInfo");
			jsoncontent1.put("objectApiName", "tp_sys_user");
			jsoncontent1.put("expressions", "select * from tp_sys_user where login_name='" + login_name + "' and pwd='"+login_pwd+"'");

			String resultselectpwdquery = operate(url+"openApi/common", jsoncontent1.toString(),adminAccessToken);
			JSONObject selectpwd_result = JSONObject.fromObject(resultselectpwdquery);
			String pwddate = selectpwd_result.get("data") == null ? "" : selectpwd_result.getString("data");
			JSONArray dataArray = new JSONArray();
			dataArray = JSONArray.fromObject(pwddate);
			if (dataArray.size() == 0) {
				resultInfo = new JSONObject();
				resultInfo.put("SuccessFlag", "1");
				resultInfo.put("ErrorMessage", "用户名或密码错误");
				resultInfo.put("ReturnData", "");
				return resultInfo;
			} else {
				String useraccessToken = gettoken(login_name);
				resultInfo.put("accessToken", useraccessToken);
				resultInfo.put("SuccessFlag", "success");
			}
		}
		return resultInfo;

	}
	public static String gettoken(String login_name) throws Exception {
		JSONObject jsoncontent = new JSONObject();
		jsoncontent.put("username", login_name);
		jsoncontent.put("safetyMark", safetyMark);
		jsoncontent.put("clientId", clientId);
		jsoncontent.put("secretKey", secretKey);
		jsoncontent.put("orgId", orgId);
		jsoncontent.put("grant_type", "password");
		URL tokenurl = null;
		String returnContent = "";
		try {
			tokenurl = new URL(url+"api/cauth/token");
			HttpURLConnection urlConnection = (HttpURLConnection) tokenurl.openConnection();
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty("Content-Type", "application/json");
			urlConnection.getOutputStream().write(jsoncontent.toString().getBytes("UTF-8"));
			urlConnection.connect();
			//获取状态码
			int code = urlConnection.getResponseCode();
			InputStream raw;
			if (code == 200) {
				InputStream in = urlConnection.getInputStream();
				raw = new BufferedInputStream(in);
			} else {
				raw = urlConnection.getErrorStream();// HttpURLConnection 才有getErrorStream方法
			}
			//放入缓存流
			//最后使用Reader接收
			Reader r = new InputStreamReader(raw);
			//打印输出
			int c;
			while((c = r.read())>0){
				returnContent +=(char)c;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(returnContent);

		JSONObject dJson = JSONObject.fromObject(jsonObject.get("data").toString());
		String accessToken = dJson.get("accessToken").toString();
		return accessToken;
	}

	public static String operate(String url_str, String data_str, String accessToken) throws Exception {
		URL tokenurl = null;
		String returnContent = "";
		try {
			tokenurl = new URL(url_str);
			HttpURLConnection urlConnection = (HttpURLConnection) tokenurl.openConnection();
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty("Content-Type", "application/json");
			urlConnection.addRequestProperty("accessToken", accessToken);
			urlConnection.getOutputStream().write(data_str.toString().getBytes("UTF-8"));
			urlConnection.connect();
			//获取状态码
			int code = urlConnection.getResponseCode();
			InputStream raw;
			if (code == 200) {
				InputStream in = urlConnection.getInputStream();
				raw = new BufferedInputStream(in);
			} else {
				raw = urlConnection.getErrorStream();// HttpURLConnection 才有getErrorStream方法
			}
			//放入缓存流
			//最后使用Reader接收
			Reader r = new InputStreamReader(raw);
			//打印输出
			int c;
			while((c = r.read())>0){
				returnContent +=(char)c;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return returnContent;
	}
}
